package com.zp.common.oss.file;

import com.zp.common.core.utils.CommonUtils;
import com.zp.common.core.utils.DateUtils;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.oss.config.FileConfig;
import com.zp.common.oss.config.uploadMessage;
import com.zp.common.oss.exception.file.FileNameLengthLimitExceededException;
import com.zp.common.oss.exception.file.FileSizeLimitExceededException;
import com.zp.common.oss.exception.file.InvalidExtensionException;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * 文件上传工具类
 *
 * @author pacs
 */
public class FileUploadUtils {
    /**
     * 默认大小 50M
     */
    public static final long DEFAULT_MAX_SIZE = 50 * 1024 * 1024;

    /**
     * 默认的文件名最大长度 100
     */
    public static final int DEFAULT_FILE_NAME_LENGTH = 100;

    /**
     * 默认上传的地址 String mpcUrl = SpringUtil.getProperty("MPC_URL");
     */
    private static String defaultBaseDir = FileConfig.getStaticPath();

    public static String getDefaultBaseDir () {
        return defaultBaseDir;
    }

    public void setDefaultBaseDir (String defaultBaseDir) {
        FileUploadUtils.defaultBaseDir = defaultBaseDir;
    }

    /**
     * 以默认配置进行文件上传
     *
     * @param file 上传的文件
     * @return 文件名称
     * @throws Exception
     */
    public static final String upload (MultipartFile file) throws IOException {
        try {
            return upload(getDefaultBaseDir(), file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 根据文件路径上传
     *
     * @param baseDir 相对应用的基目录
     * @param file    上传的文件
     * @return 文件名称
     * @throws IOException
     */
    public static final uploadMessage uploadTemplate (String baseDir, MultipartFile file) throws IOException {
        uploadMessage uploadMessage = new uploadMessage();
        try {
            return uploadTemplate(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    public static final uploadMessage uploadfileReport (String baseDir, MultipartFile file, String classtype, String businessType, int tempsum) throws IOException {
        uploadMessage uploadMessage = new uploadMessage();
        try {
            return uploadTemplate(baseDir, file, classtype, businessType, tempsum, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    public static final uploadMessage uploadTemplate (String baseDir, MultipartFile file, String classType,
                                                      String businessType, int tempSum, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException, InvalidExtensionException {
        int fileNameLength = Objects.requireNonNull(file.getOriginalFilename()).length();
        if (fileNameLength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        assertAllowed(file, allowedExtension);
        String fileName = extractFilename(file, classType, businessType, tempSum);
        File desc = getAbsoluteFileReport(baseDir, fileName);
        file.transferTo(desc);
        String pathFile = desc.getPath();
        String urlFile = getPathFileName(baseDir, fileName);
        uploadMessage uploadMessage = new uploadMessage();
        uploadMessage.setFilePath(pathFile);
        uploadMessage.setFileUrl(urlFile);
        return uploadMessage;
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename (MultipartFile file, String classtype, String businessType, int tempsum) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        String tempsumStr = tempsum == 0 ? "" : String.valueOf(tempsum);
        fileName = businessType + File.separator + classtype + File.separator + tempsum + File.separator + "reportTemplate" + tempsumStr + "." + extension;
        return fileName;
    }

    public static File getAbsoluteFileReport (String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        desc.delete();
        if (!desc.exists()) {
            desc.createNewFile();
        }
        return desc;
    }

    private static int getFileNameLength (MultipartFile file) {
        if (ObjectUtils.isNotEmpty(file)) {
            return Objects.requireNonNull(file.getOriginalFilename()).length();
        }
        return 0;
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final uploadMessage uploadTemplate (String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        if (getFileNameLength(file) > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        assertAllowed(file, allowedExtension);
        String fileName = extractFilename(file);
        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        String pathFile = desc.getPath();
        String urlFile = getPathFileName(baseDir, fileName);
        uploadMessage uploadMessage = new uploadMessage();
        uploadMessage.setFilePath(pathFile);
        uploadMessage.setFileUrl(urlFile);
        return uploadMessage;
    }

    public static final String upload (String baseDir, MultipartFile file) throws IOException {
        try {
            return upload(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    //用于患者检查图像上传
    public static final String exmupLoad (String baseDir, MultipartFile file, String examrequestid) throws IOException {
        try {
            return exmupLoad(baseDir, file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION, examrequestid);
        } catch (Exception e) {
            throw new IOException(e.getMessage(), e);
        }
    }

    /**
     * 文件上传
     *
     * @param baseDir          相对应用的基目录
     * @param file             上传的文件
     * @param allowedExtension 上传文件类型
     * @return 返回上传成功的文件名
     * @throws FileSizeLimitExceededException       如果超出最大大小
     * @throws FileNameLengthLimitExceededException 文件名太长
     * @throws IOException                          比如读写文件出错时
     * @throws InvalidExtensionException            文件校验异常
     */
    public static final String upload (String baseDir, MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        if (getFileNameLength(file) > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        assertAllowed(file, allowedExtension);
        String fileName = extractFilename(file);
        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        return getPathFileName(baseDir, fileName);
    }

    public static final String exmupLoad (String baseDir, MultipartFile file, String[] allowedExtension, String examrequestid)
            throws FileSizeLimitExceededException, IOException, FileNameLengthLimitExceededException,
            InvalidExtensionException {
        if (getFileNameLength(file) > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH) {
            throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
        }
        assertAllowed(file, allowedExtension);
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + File.separator + examrequestid + File.separator + CommonUtils.getUUID() + "." + extension;
        File desc = getAbsoluteFile(baseDir, fileName);
        file.transferTo(desc);
        return getPathFileName(baseDir, fileName);
    }

    /**
     * 编码文件名
     */
    public static final String extractFilename (MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        fileName = DateUtils.datePath() + File.separator + CommonUtils.getUUID() + "." + extension;
        return fileName;
    }

    private static final File getAbsoluteFile (String uploadDir, String fileName) throws IOException {
        File desc = new File(uploadDir + File.separator + fileName);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        if (!desc.exists()) {
            // desc.createNewFile();
        }
        return desc;
    }

    public static final String getPathFileName (String uploadDir, String fileName) throws IOException {
        int dirLastIndex = FileConfig.getStaticPath().length() + 1;
        String currentDir = StringUtils.substring(uploadDir, dirLastIndex);
        return currentDir + File.separator + fileName;
//        return Constants.RESOURCE_PREFIX + currentDir + File.separator + fileName;
    }

    /**
     * 文件大小校验
     *
     * @param file 上传的文件
     * @return
     * @throws FileSizeLimitExceededException 如果超出最大大小
     * @throws InvalidExtensionException
     */
    public static final void assertAllowed (MultipartFile file, String[] allowedExtension)
            throws FileSizeLimitExceededException, InvalidExtensionException {
        long size = file.getSize();
        if (DEFAULT_MAX_SIZE != -1 && size > DEFAULT_MAX_SIZE) {
            throw new FileSizeLimitExceededException(DEFAULT_MAX_SIZE / 1024 / 1024);
        }

        String fileName = file.getOriginalFilename();
        String extension = getExtension(file);
        if (allowedExtension != null && !isAllowedExtension(extension, allowedExtension)) {
            if (allowedExtension == MimeTypeUtils.IMAGE_EXTENSION) {
                throw new InvalidExtensionException.InvalidImageExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.FLASH_EXTENSION) {
                throw new InvalidExtensionException.InvalidFlashExtensionException(allowedExtension, extension,
                        fileName);
            } else if (allowedExtension == MimeTypeUtils.MEDIA_EXTENSION) {
                throw new InvalidExtensionException.InvalidMediaExtensionException(allowedExtension, extension,
                        fileName);
            } else {
                throw new InvalidExtensionException(allowedExtension, extension, fileName);
            }
        }

    }

    /**
     * 判断MIME类型是否是允许的MIME类型
     *
     * @param extension
     * @param allowedExtension
     * @return
     */
    public static final boolean isAllowedExtension (String extension, String[] allowedExtension) {
        for (String str : allowedExtension) {
            if (str.equalsIgnoreCase(extension)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件名的后缀
     *
     * @param file 表单文件
     * @return 后缀名
     */
    public static final String getExtension (MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if (StringUtils.isEmpty(extension)) {
            extension = MimeTypeUtils.getExtension(Objects.requireNonNull(file.getContentType()));
        }
        return extension;
    }

    public static final void fileConvertBinaryStream (String templateUrl, HttpServletRequest request, HttpServletResponse response) {
        // path是指欲下载的文件的路径。
        File file = new File(templateUrl);
        // 取得文件名。
        String filename = file.getName();
        // 取得文件的后缀名。
        String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
        if (!file.exists()) {
            throw new RuntimeException("文件不存在，请重新上传后再进行下载");
        }
        try {
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes()));
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(Files.newInputStream(Paths.get(templateUrl)));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
            // 清空response
            response.reset();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 下载未知类型文件
     *
     * @param templateUrl
     * @param request
     * @param response
     */
    public static void downLoadFile (String templateUrl, HttpServletRequest request, HttpServletResponse response) {
        // 设置response的Header
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.setContentType("application/octet-stream");
        fileConvertBinaryStream(templateUrl, request, response);
    }

    public static void printPdf (String templateUrl, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("application/pdf");
        fileConvertBinaryStream(templateUrl, request, response);
    }
}
